package com.supply.dl.widget.viewpagerindicator;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.supply.dl.R;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;

/**
 * 类描述：　[军械库顶部按钮的tab]<br/>
 * 项目名称：[ForumApp]<br/>
 * 包名：　　[com.forum.app.widget]<br/>
 * 创建人：　[杨挺]<br/>
 * 创建时间：[2015/1/13 11:36]<br/>
 * 公司：　　[成都畅聊科技]<br/>
 * 版本：　　[v1.0.0]<br/>
 */
public class TabPageIndicator extends HorizontalScrollView implements PageIndicator
{
	/**
	 * Title text used when no title is provided by the adapter.
	 */
	private static final CharSequence EMPTY_TITLE = "";

	/**
	 * Interface for a callback when the selected tab has been reselected.
	 */
	public interface OnTabReselectedListener
	{
		/**
		 * Callback when the selected tab has been reselected.
		 *
		 * @param position Position of the current center item.
		 */
		void onTabReselected(int position);
	}

	/**
	 * Interface for a callback when the selected tab has been reselected.
	 */
	public interface OnTabClickListener
	{
		/**
		 * Callback when the selected tab has been reselected.
		 *
		 * @param position Position of the current center item.
		 */
		void onClick(int position);
	}

	public interface OnCreateTabItemListener
	{
		View onCreateItem(int position, CharSequence title);
	}

	private Runnable mTabSelector;

	private Context mContext;

	private boolean hasVerticalLine = true;

//	private int defaultLineResId = R.drawable.the_vertical_line;

	private final OnClickListener mTabClickListener = new OnClickListener()
	{
		public void onClick(View view)
		{
			TabView tabView = (TabView) view;
			final int oldSelected = mViewPager.getCurrentItem();
			final int newSelected = tabView.getIndex();
			mViewPager.setCurrentItem(newSelected, hasCurrentAnima);
			if (onTabClickListener != null)
			{
				onTabClickListener.onClick(newSelected);
			}
			if (oldSelected == newSelected && mTabReselectedListener != null)
			{
				mTabReselectedListener.onTabReselected(newSelected);
			}
		}
	};

	private final LinearLayout mTabLayout;

	private ViewPager mViewPager;
	private ViewPager.OnPageChangeListener mListener;

	private int mMaxTabWidth;
	private int mSelectedTabIndex;

	private OnTabReselectedListener mTabReselectedListener;
	private OnTabClickListener onTabClickListener;

	private OnCreateTabItemListener onCreateTabItemListener;

	private boolean hasCurrentAnima = true;

	public TabPageIndicator(Context context)
	{
		this(context, null);
	}

	public TabPageIndicator(Context context, AttributeSet attrs)
	{
		super(context, attrs);
		this.mContext = context;
		setHorizontalScrollBarEnabled(false);
		mTabLayout = new LinearLayout(context);
		if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB)
		{
			mTabLayout.setMotionEventSplittingEnabled(false);
		}
		addView(mTabLayout, new ViewGroup.LayoutParams(WRAP_CONTENT, MATCH_PARENT));
	}

	public void setOnTabClickListener(OnTabClickListener onTabClickListener)
	{
		this.onTabClickListener = onTabClickListener;
	}

	public void setHasCurrentAnima(boolean hasCurrentAnima)
	{
		this.hasCurrentAnima = hasCurrentAnima;
	}

	public void setOnCreateTabItemListener(OnCreateTabItemListener onCreateTabItemListener)
	{
		this.onCreateTabItemListener = onCreateTabItemListener;
	}

	public void setOnTabReselectedListener(OnTabReselectedListener listener)
	{
		mTabReselectedListener = listener;
	}

//	public void setDefaultLineResId(int defaultLineResId)
//	{
//		this.defaultLineResId = defaultLineResId;
//	}

	public void setHasVerticalLine(boolean hasVerticalLine)
	{
		this.hasVerticalLine = hasVerticalLine;
	}

	@Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
	{
		final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
		final boolean lockedExpanded = widthMode == MeasureSpec.EXACTLY;
		setFillViewport(lockedExpanded);

		final int childCount = mTabLayout.getChildCount();
		if (childCount > 1 && (widthMode == MeasureSpec.EXACTLY || widthMode == MeasureSpec.AT_MOST))
		{
			if (childCount > 2)
			{
				mMaxTabWidth = (int) (MeasureSpec.getSize(widthMeasureSpec) * 0.4f);
			}
			else
			{
				mMaxTabWidth = MeasureSpec.getSize(widthMeasureSpec) / 2;
			}
		}
		else
		{
			mMaxTabWidth = -1;
		}

		final int oldWidth = getMeasuredWidth();
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		final int newWidth = getMeasuredWidth();

		if (lockedExpanded && oldWidth != newWidth)
		{
			// Recenter the tab display if we're at a new (scrollable) size.
			setCurrentItem(mSelectedTabIndex);
		}
	}

	private void animateToTab(final int position)
	{
		final View tabView = mTabLayout.getChildAt(position);
		if (mTabSelector != null)
		{
			removeCallbacks(mTabSelector);
		}
		mTabSelector = new Runnable()
		{
			public void run()
			{
				final int scrollPos = tabView.getLeft() - (getWidth() - tabView.getWidth()) / 2;
				smoothScrollTo(scrollPos, 0);
				mTabSelector = null;
			}
		};
		post(mTabSelector);
	}

	@Override public void onAttachedToWindow()
	{
		super.onAttachedToWindow();
		if (mTabSelector != null)
		{
			// Re-post the selector we saved
			post(mTabSelector);
		}
	}

	@Override public void onDetachedFromWindow()
	{
		super.onDetachedFromWindow();
		if (mTabSelector != null)
		{
			removeCallbacks(mTabSelector);
		}
	}

	private void addTab(int index, int count, CharSequence text)
	{
		final TabView tabView = new TabView(mContext, index);
		if (onCreateTabItemListener != null)
		{
			try
			{
				View itemView = onCreateTabItemListener.onCreateItem(index, text);

				LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, MATCH_PARENT, 1);
				tabView.addView(itemView, lp);
				if (hasVerticalLine && count > 1)
				{
					if (index != count - 1)
					{
						ImageView imageView = new ImageView(mContext);
//						imageView.setImageResource(defaultLineResId);
						LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(WRAP_CONTENT, MATCH_PARENT);
						params.gravity = Gravity.CENTER;
						tabView.addView(imageView, params);
					}
				}
			}
			catch (Exception e)
			{
				//LogManager.getLogger().d(Constants.Config.TAG, "TabPageIndicator addTab(...) err|" + e.toString(), e);
			}
		}
		tabView.setOnClickListener(mTabClickListener);
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, MATCH_PARENT, 1);
//		int vMargin = DisplayUtils.dip2px(mContext, 8);
//		lp.setMargins(0, vMargin, 0, vMargin);
		mTabLayout.addView(tabView, lp);
	}

	/**
	 * 将像素值px转换为dp
	 */
	public float dip2px(Context ctx, int dpValue)
	{
		float scale = ctx.getResources().getDisplayMetrics().density;
		return dpValue * scale;
	}

	@Override public void onPageScrollStateChanged(int arg0)
	{
		if (mListener != null)
		{
			mListener.onPageScrollStateChanged(arg0);
		}
	}

	@Override public void onPageScrolled(int arg0, float arg1, int arg2)
	{
		if (mListener != null)
		{
			mListener.onPageScrolled(arg0, arg1, arg2);
		}
	}

	@Override public void onPageSelected(int arg0)
	{
		setCurrentItem(arg0);
		if (mListener != null)
		{
			mListener.onPageSelected(arg0);
		}
	}

	@Override public void setViewPager(ViewPager view)
	{
		if (mViewPager == view)
		{
			return;
		}
		if (mViewPager != null)
		{
			mViewPager.setOnPageChangeListener(null);
		}
		final PagerAdapter adapter = view.getAdapter();
		if (adapter == null)
		{
			throw new IllegalStateException("ViewPager does not have adapter instance.");
		}
		mViewPager = view;
		view.setOnPageChangeListener(this);
		notifyDataSetChanged();
	}

	@Override public ViewPager getViewPager()
	{
		return mViewPager;
	}

	public void notifyDataSetChanged()
	{
		mTabLayout.removeAllViews();
		PagerAdapter adapter = mViewPager.getAdapter();
		final int count = adapter.getCount();
		for (int i = 0; i < count; i++)
		{
			CharSequence title = adapter.getPageTitle(i);
			if (title == null)
			{
				title = EMPTY_TITLE;
			}
			addTab(i, count, title);
		}
		if (mSelectedTabIndex > count)
		{
			mSelectedTabIndex = count - 1;
		}
		setCurrentItem(mSelectedTabIndex);
		requestLayout();
	}

	@Override public void setViewPager(ViewPager view, int initialPosition)
	{
		setViewPager(view);
		setCurrentItem(initialPosition);
	}

	@Override public void setCurrentItem(int item)
	{
		if (mViewPager == null)
		{
//			throw new IllegalStateException("ViewPager has not been bound.");
			return;
		}
		mSelectedTabIndex = item;
		mViewPager.setCurrentItem(item);

		final int tabCount = mTabLayout.getChildCount();
		for (int i = 0; i < tabCount; i++)
		{
			final View child = mTabLayout.getChildAt(i);
			final boolean isSelected = (i == item);
			child.setSelected(isSelected);
			if (isSelected)
			{
				animateToTab(item);
			}
		}
	}

	@Override public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener)
	{
		mListener = listener;
	}

	private class TabView extends LinearLayout
	{
		private int mIndex;

		public TabView(Context context, int mIndex)
		{
			super(context);
			this.mIndex = mIndex;
		}

		@Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
		{
			super.onMeasure(widthMeasureSpec, heightMeasureSpec);
			// Re-measure if we went beyond our maximum size.
			if (mMaxTabWidth > 0 && getMeasuredWidth() > mMaxTabWidth)
			{
				super.onMeasure(MeasureSpec.makeMeasureSpec(mMaxTabWidth, MeasureSpec.EXACTLY), heightMeasureSpec);
			}
//			else
//				super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		}

		public int getIndex()
		{
			return mIndex;
		}
	}
}
